<template>
    <el-card>
     <h1>部门表格</h1>
     <el-button type="primary" style="float: right;" @click="dialogVisible = true">新增</el-button>
     <el-table :data="tableData.deptList" border style="width: 100%" >
       <el-table-column type="index" label="序号" width="180" />
       <el-table-column prop="name" label="姓名" width="180" />
       <el-table-column prop="tel" label="部门电话" width="180" />
       <el-table-column prop="principal" label="部门联系人" width="180" />
       <el-table-column prop="principal_tel" label="联系人电话" width="180" />
       <el-table-column  label="操作" >
         <template v-slot="{row}">
             <!-- {{ row.id}} -->
             <el-button type="warning" @click="updateDialog(row.id)">编辑</el-button>
 
            <el-button type="danger" @click="confirmDelete(row.id)">
                        删除
            </el-button>
 
         </template>
       </el-table-column  >
     </el-table>
 
     <!-- 分页功能 -->
     <div class="demo-pagination-block">
     <!-- <div class="demonstration">All combined</div> -->
     <el-pagination
       v-model:current-page="currentPage4"
       v-model:page-size="pageSize4"
       :page-sizes="[5, 10, 20, 30]"
       :size="size"
       :disabled="disabled"
       :background="background"
       layout="total, sizes, prev, pager, next, jumper"
       :total="tableData.total"
       @size-change="handleSizeChange"
       @current-change="handleCurrentChange"
     />
   </div>
    </el-card>
    <!-- 新增窗口 -->
    <el-dialog
    v-model="dialogVisible"
    title="新增部门"
    width="500"
    :before-close="handleClose"
  >
    <!-- 表单验证 -->
      <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="ruleForm.name" />
    </el-form-item>
    <el-form-item label="部门电话" prop="tel">
      <el-input v-model="ruleForm.tel" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="principal">
      <el-input v-model="ruleForm.principal" />
    </el-form-item>
    <el-form-item label="负责人电话" prop="principal_tel">
      <el-input v-model="ruleForm.principal_tel" />
    </el-form-item>
  </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef);">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef);">
         确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改功能 -->
  <el-dialog
    v-model="updateVisible"
    title="修改部门"
    width="500"
    :before-close="handleClose"
  >
  <!-- <h1 >{{  updateId }}</h1> -->
    <!-- 表单验证 -->
      <el-form
    ref="updateFormRef"
    style="max-width: 600px"
    :model="updateObj.obj"
    :rules="rules"
    label-width="auto"
  >

  

    <el-form-item label="部门名称" prop="name">
      <el-input v-model=" updateObj.obj.name" />
    </el-form-item>
    <el-form-item label="部门电话" prop="tel">
      <el-input v-model=" updateObj.obj.tel" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="principal">
      <el-input v-model=" updateObj.obj.principal" />
    </el-form-item>
    <el-form-item label="负责人电话" prop="principal_tel">
      <el-input v-model=" updateObj.obj.principal_tel" />
    </el-form-item>
  </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetUpdate(updateFormRef);">取消</el-button>
        <el-button type="primary" @click="submitUpdate(updateFormRef);">
         确认
        </el-button>
      </div>
    </template>
  </el-dialog>



   </template>
   
   <script lang="ts" setup>
 import { ElMessage, ElNotification, ElMessageBox,FormInstance, FormRules  } from 'element-plus';
 import { inject, onMounted, reactive, ref } from 'vue';
   
 import { findDeptByPage,deleteById,findById,updateById,insertDept} from '@/api/dept';

 //封装了axios，所以不用导入
  //  let axios:any=inject('axios');

   const tableData = reactive({
      deptList:[],
       // 部门请求参数
      queryInfo : {
         query:"",
         pageNum : 1,
         pageSize: 7
     },
     total:0
   })
  //  let updateId=ref(0);
 
   async function findAllDept(){
      const {data}=await findDeptByPage(tableData.queryInfo);
     //  console.log(data);
 
     if(data.code==200){
         tableData.deptList=data.data.rows;
         tableData.total=data.data.total;
 
       //弹出提示success
 //     ElMessage({
 //     message: '查询成功',
 //     type: 'success',
 //   })
     }else{
         ElMessage.error('查询失败')
     }
      
   }
 
   async function deleteByDeptId(id: any){
      const {data} =await deleteById(id);
       
       if(data.code==200){
  //        ElNotification({
  //    title: 'Success',
  //    message: '删除成功',
  //    type: 'success',
  //  })
         findAllDept();
         
       }else{
         ElMessage.error('删除失败')
       }
   }
 
   const confirmDelete = async (id: any) => {
     try {
       await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
       });
       await deleteByDeptId(id);
     } catch (error) {
       // 用户点击取消时会进入这里，可留空
     }
   };
 
   onMounted(()=>{
     findAllDept();
   })
 
   // 分页功能
 import type { ComponentSize } from 'element-plus'
import { dateTableEmits } from 'element-plus/es/components/calendar/src/date-table.mjs';
 
 
 const currentPage4 = ref(1)

 const pageSize4 = ref(5)
 const size = ref<ComponentSize>('default')
 const background = ref(false)
 const disabled = ref(false)
 
 // 分页显示数据
 const handleSizeChange = (val: number) => {
 //   console.log(`${val} items per page`)
     tableData.queryInfo.pageSize=val;
     findAllDept();
 }
 const handleCurrentChange = (val: number) => {
 //   console.log(`current page: ${val}`)
   tableData.queryInfo.pageNum=val;
   findAllDept();
 }


// 新增功能
let dialogVisible = ref(false)

// 修改功能
let updateVisible = ref(false)

const updateFormRef= ref<FormInstance>()

let updateObj=reactive({
  obj:{}
})

//编辑功能
async function updateDialog(id:number){
    updateVisible.value=true
    const {data} =await findById(id);
    console.log(data);
    updateObj.obj=data.data;
}


const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定关闭吗？')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

interface RuleForm {
  name: string
  tel:string
  principal:string
  principal_tel:string
  
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: '',
  tel:"",
  principal:'',
  principal_tel:''
 
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '部门名称不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '部门名称应该在3~10个字之间', trigger: 'blur' },
  ],
  tel: [
    { required: true, message: '部门电话不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '部门电话应该在8~11位之间', trigger: 'blur' },
  ],
 
})

//新增方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate( async(valid, fields) => {
    if (valid) {
        const {data}= await insertDept(ruleForm);
          if(data.code==200){
            alert('新增成功');
            findAllDept();
          }
    } else {
      console.log('error submit!', fields)
    }
  })
  resetForm(formEl);
}

const resetForm = (formEl: FormInstance | undefined) => {
  dialogVisible.value=false
  if (!formEl) return
  formEl.resetFields()
}

//修改方法
const submitUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate( async(valid, fields) => {
    if (valid) {
        //  await axios.put('/dep/'+updateObj.obj.id,updateObj.obj);
         await updateById(updateObj.obj.id,updateObj.obj);
            findAllDept();
          
    } else {
      console.log('error submit!', fields)
    }
  })
  resetUpdate(formEl);
}

const resetUpdate = (formEl: FormInstance | undefined) => {
  updateVisible.value=false
  if (!formEl) return
  formEl.resetFields()
}


   </script>
 
 <style scoped>
 /* 分页样式 */
 .demo-pagination-block{
     margin-top: 20px;
 }
 
 .demo-pagination-block + .demo-pagination-block {
   margin-top: 10px;
 }
 .demo-pagination-block .demonstration {
   margin-bottom: 16px;
 }
 </style>    